[Ruby] Modifying object inside a loop doesn't change object outside of the loop?

Posted by Jergason on Stack Overflow See other posts from Stack Overflow or by Jergason
Published on 2010-04-14T03:20:39Z Indexed on 2010/04/14 3:22 UTC
Read the original article Hit count: 226

Filed under:
|

I am having problems with modifying objects inside blocks and not getting the expected values outside the blocks. This chunk of code is supposed to transform a bunch of points in 3d space, calculate a score (the rmsd or root mean squared deviation), and store both the score and the set of points that produced that score if it is lower than the current lowest score. At the end, I want to print out the best bunch of points.

first = get_transformed_points(ARGV[0])
second = get_transformed_points(ARGV[1])

best_rmsd = first.rmsd(second)
best_points = second

#transform the points around x, y, and z and get the rmsd. If the new points
# have a smaller rmsd, store them.
ROTATION = 30 #rotate by ROTATION degrees
num_rotations = 360/ROTATION
radians = ROTATION * (Math::PI/180)

num_rotations.times do |i|
    second = second * x_rotate
    num_rotations.times do |j|
        second = second * y_rotate
        num_rotations.times do |k|
            second = second * z_rotate
            rmsd = first.rmsd(second)
            if rmsd < best_rmsd then
                best_points = second
                best_rmsd = rmsd
            end
        end
    end
end
File.open("#{ARGV[1]}.out", "w") {|f| f.write(best_points.to_s)}

I can print out the points that are getting stored inside the block, and they are getting transformed and stored correctly. However, when I write out the points to a file at the end, they are the same as the initial set of points. Somehow the best_points = second chunk doesn't seem to be doing anything outside of the block.

It seems like there are some scoping rules that I don't understand here. I had thought that since I declared and defined best_points above, outside of the blocks, that it would be updated inside the blocks. However, it seems that when the blocks end, it somehow reverts back to the original value. Any ideas how to fix this? Is this a problem with blocks specifically?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about scope